package fr.lille.inria.adam.lifl.EcoGardeInventory.Utils;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.os.ResultReceiver;
import fr.lille.inria.adam.lifl.EcoGardeInventory.Services.ExecuteRequest;

public class RestService{
	
	private final Handler mHandler;
	private ArrayList <ParcelableNameValuePair> mParams;
	private ArrayList <ParcelableNameValuePair> mHeaders;
	private String mUrl;
	private Context mContext;

	public RestService(Handler mHandler, Context mContext, String url){
		this.mHandler = mHandler;
		
		this.mContext = mContext;
		
		this.mUrl = url;
		
		mParams = new ArrayList<ParcelableNameValuePair>();
		
		mHeaders = new ArrayList<ParcelableNameValuePair>();
	}

	public void addParam(String name, String value){
		mParams.add(new ParcelableNameValuePair(name, value));
	}

	public void addHeader(String name, String value){
		mHeaders.add(new ParcelableNameValuePair(name,value));
	}
	
	public void execute(int method) {
	     ResultReceiver mReceiver;
	     
	     mReceiver = new ResultReceiver(mHandler){
    	    @Override
    	    protected void onReceiveResult(int resultCode, Bundle resultData) {
    	    	mHandler.obtainMessage(0,0,0,resultData.getString("result")).sendToTarget();
    	    }
	     };
	     
	     final Intent mIntent = new Intent(mContext, ExecuteRequest.class);
	     
	     mIntent.putParcelableArrayListExtra("headers", (ArrayList<? extends Parcelable>) mHeaders);
	     
	     mIntent.putExtra("params", mParams);
	     
	     mIntent.putExtra("url", mUrl);
	     
	     mIntent.putExtra("receiver", mReceiver);
	     
	     mIntent.putExtra("method", method);
	     
	     mContext.startService(mIntent);
	}
}